#pragma once

#include "InetAddr.hpp"
#include "log.hpp"
#include "Mutex.hpp"
#include <vector>

using namespace LogModule;

class Route
{
    bool Exist(InetAddr& peer)
    {
        for(auto& user : _online_user)
        {
            if(user == peer)
            {
                return true;
            }
        }
        return false;
    }

    void Add(InetAddr& peer)
    {
        LOG(LogLevel::INFO) << "新增一个在线用户" << peer.StringAddr();
        _online_user.push_back(peer);
    }

    void Delete(const InetAddr& peer)
    {
        for(auto it = _online_user.begin(); it != _online_user.end(); it++)
        {
            if(*it == peer)
            {
                _online_user.erase(it);
                break;
            }
        }
    }
public:
void MessageRoute(int sockfd, const std::string& message, InetAddr& peer)
{
    MutexGuard mx(Mutex);
    if(!Exist(peer))
    {
        Add(peer);
    }
    
    std::string send_message = peer.StringAddr() + " say: " + message;
    //LOG(LogLevel::DEBUG) << send_message;

    //给所有在线用户发送消息
    for(auto& user : _online_user)
    {
        int ret = sendto(sockfd, send_message.c_str(), send_message.size(), 0, (const struct sockaddr*)&user.NetAddr(), sizeof user.NetAddr());
        if(ret < 0) LOG(LogLevel::ERROR) << "send error";
    }

    if(message == "QUIT")
    {
        LOG(LogLevel::INFO) << "删除一个在线用户" << peer.StringAddr();
        Delete(peer);
    }
}
private:
    std::vector<InetAddr> _online_user; // 在线用户
    Mutex _mutex;
};